# -*- coding: utf-8 -*-
"""
问答API接口

功能说明:
- 提供RESTful问答API接口
- 处理智能问答请求和响应
- 集成问答服务层
- 支持多轮对话和上下文管理

作者: MetasoCreator Team
创建时间: 2025-08-19
"""

from flask import request, current_app
from flask_restx import Namespace, Resource, fields
from typing import Dict, Any, List
import logging
from datetime import datetime

from services.qa_service import QAService
from utils.helpers import validate_request_data, create_api_response

# 创建问答命名空间
qa_ns = Namespace('chat', description='智能问答相关API接口')
logger = logging.getLogger(__name__)

# 定义消息模型
message_model = qa_ns.model('Message', {
    'role': fields.String(required=True, description='消息角色', enum=['user', 'assistant', 'system'], example='user'),
    'content': fields.String(required=True, description='消息内容', example='什么是人工智能？')
})

# 定义请求模型
qa_request_model = qa_ns.model('QARequest', {
    'messages': fields.List(fields.Nested(message_model), required=True, description='对话消息列表'),
    'scope': fields.String(description='搜索范围', enum=['webpage', 'document', 'scholar', 'podcast', 'image', 'video'], default='webpage'),
    'model': fields.String(description='使用模型（支持 fast_thinking / deep_thinking / da_vinci / gpt-4）', default='fast_thinking')
})

# 文档模型（不强制序列化）
qa_response_model = qa_ns.model('QAResponse', {
    'success': fields.Boolean(description='请求是否成功'),
    'message': fields.String(description='响应消息'),
    'data': fields.Raw(description='问答结果数据'),
    'timestamp': fields.String(description='响应时间戳')
})


@qa_ns.route('/completions')
class QAResource(Resource):
    @qa_ns.doc('ask_question')
    @qa_ns.expect(qa_request_model)
    def post(self):
        """
        智能问答接口
        """
        try:
            data = request.get_json()
            if not data:
                return create_api_response(False, "请求体不能为空", status_code=400)
            
            messages = data.get('messages')
            if not messages or not isinstance(messages, list) or len(messages) == 0:
                return create_api_response(False, "messages必须是非空列表", status_code=400)
            
            # 基础消息校验
            for i, message in enumerate(messages):
                if not isinstance(message, dict) or 'role' not in message or 'content' not in message:
                    return create_api_response(False, f"messages[{i}]必须包含'role'和'content'字段", status_code=400)
                if message['role'] not in ['user', 'assistant', 'system']:
                    return create_api_response(False, f"messages[{i}].role必须是'user'、'assistant'或'system'", status_code=400)
                if not str(message['content']).strip():
                    return create_api_response(False, f"messages[{i}].content不能为空", status_code=400)
            
            scope = data.get('scope')
            if scope:
                valid_scopes = ['webpage', 'document', 'scholar', 'podcast', 'image', 'video']
                if scope not in valid_scopes:
                    return create_api_response(False, f"无效的搜索范围: {scope}，有效值为: {', '.join(valid_scopes)}", status_code=400)
            
            # 委托服务层执行
            service = QAService()
            result = service.ask_question(messages=messages, scope=scope, model=data.get('model'))
            
            # 透传上游或服务层生成的标准结构
            # 若 result.success 显式为 False，返回 500，否则 200
            if isinstance(result, dict) and result.get('success') is False:
                return result, 500
            return result, 200
        except Exception:
            return create_api_response(False, "服务器内部错误", status_code=500)


@qa_ns.route('/test')
class QATestResource(Resource):
    @qa_ns.doc('test_qa_api')
    def get(self):
        try:
            return create_api_response(True, "问答API正常", data={
                'service_status': 'running',
                'api_version': '1.0',
                'timestamp': datetime.now().isoformat()
            })
        except Exception:
            return create_api_response(False, "问答API异常", status_code=500)